/**
 * Created by Kiva on 17/1/20.
 */


$.fn.extend({
    billingtree:function(options) {
        var $tree = this;
        $tree.options = $.extend($.fn.billingtree.defaults, options);
        if($tree.options.url===undefined && $tree.options.data == undefined) {
			throw new Error("请传入数据或数据地址！！！");
		}
        if(typeof $tree.options.data == "object"){
			$tree.data = $tree.options.data;
			new BillingTree($tree);
        } else {
			//ajax请求
			if (typeof $tree.options.url == "string") {
				$.ajax({
					async: $tree.options.async,
					type: "POST",
					dataType: "json",
					url: $tree.options.url,
					data: $tree.options.param,
					success: function(data, textStatus) {
						$tree.data = data;
						new BillingTree($tree);
					},
					error: function(e){
						throw new Error($tree.options.url + "请求出现例外:" + e.statusText);
					}
				});
			} else {
				throw new Error("请求地址有误！！！");
			}
        }
        return $tree;
    }
});

$.fn.billingtree.defaults={
	async: true,	//异步方式
    rootId: -1,//最高节点的idtext: "title",//显示的树节点的名称，value值表示的是json数据中的那个key
    pid : "pid",//显示和父节点关联的那个id名称，value值表示的是json数据中的那个key
    attribute : {"data-id":"id"},//放着要存在a标签中的数据 key表示的是a标签中的属性  value表示的是json数据中的key
	param : {},//url请求参数
	onclick : function(){}
};

function BillingTree($tree) {
    var options=$tree.options;
    var data=$tree.data;
    init();
    //初始化树的方法，每次运行此方法会把树清空一次，事件全部清除
    function init() {
        var $rootA = $tree.find(".nav:first").find("li:first").children("a:first");
        $rootA.find("span").removeClass("arrow-rotate").removeClass('arrow-rotate-recover');
        $rootA.siblings().remove();
        $rootA.parent().off("click");
        load($rootA);
    }


    //根据数据和setting加载树的方法
    function load($rootA) {
        var $rootLi=$tree.find("li:first");
        var html='<ul class="nav nav-second d-n" node-expanded="false">';
        $.each(data,function (i,value) {
            if(value[options.pid]==options.rootId){
                html+='<li><a  ';
                for(var attr in options.attribute){
                    html+=attr+'='+value[options.attribute[attr]]+' ';
                }
                html+='><span class="nav-label billing-leaf">'+value[options.text]+'</span> <span class="icon icon-xiangyou"></span></a></li>';
            }
        });
        html+='</ul>';
        $rootLi.append(html);
        $.each($rootA.siblings("ul").children("li"),function () {
            var $li=$(this);
            var $a=$li.children("a");
            var _blsId=$a.attr("data-id");
            html='<ul class="nav nav-third d-n" node-expanded="false">';
            $.each(data,function (i,value) {
                if(value[options.pid]==_blsId){
                    html+='<li><a  ';
                    for(var attr in options.attribute){
                        html+=attr+'='+value[options.attribute[attr]]+' ';
                    }
                    html+='><span class="nav-label billing-leaf">'+value[options.text]+'</span> <span class="icon icon-xiangyou"></span></a></li>';
                }
            });
            html+='</ul>';
            $li.append(html);
        });
        $.each($rootA.siblings("ul").children("li").children("ul").children("li"),function () {
            var $li=$(this);
            var $a=$li.children("a");
            var _blsId=$a.attr("data-id");
            html='<ul class="nav nav-fourth d-n" node-expanded="false">';
            $.each(data,function (i,value) {
                if(value[options.pid]==_blsId){
                    html+='<li><a  ';
                    for(var attr in options.attribute){
                        html+=attr+'='+value[options.attribute[attr]]+' ';
                    }
                    html+='><span class="nav-label billing-leaf">'+value[options.text]+'</span> <span class="icon icon-xiangyou"></span></a></li>';
                }
            });
            html+='</ul>';
            $li.append(html);
        });
        $.each($rootA.siblings("ul").children("li").children("ul").children("li")
        		.children("ul").children("li"),function () {
            var $li=$(this);
            var $a=$li.children("a");
            var _blsId=$a.attr("data-id");
            html='<ul class="nav nav-fifth d-n" node-expanded="false">';
            $.each(data,function (i,value) {
                if(value[options.pid]==_blsId){
                    html+='<li><a  ';
                    for(var attr in options.attribute){
                        html+=attr+'='+value[options.attribute[attr]]+' ';
                    }
                    html+='><span class="nav-label billing-leaf">'+value[options.text]+'</span> <span class="icon icon-xiangyou"></span></a></li>';
                }
            });
            html+='</ul>';
            $li.append(html);
        });
        $.each($rootA.siblings("ul").children("li").children("ul").children("li")
        		.children("ul").children("li").children("ul").children("li"),function () {
            var $li=$(this);
            var $a=$li.children("a");
            var _blsId=$a.attr("data-id");
            html='<ul class="nav nav-sixth d-n" node-expanded="false">';
            $.each(data,function (i,value) {
                if(value[options.pid]==_blsId){
                    html+='<li><a  ';
                    for(var attr in options.attribute){
                        html+=attr+'='+value[options.attribute[attr]]+' ';
                    }
                    html+='><span class="nav-label billing-leaf">'+value[options.text]+'</span> <span class="icon icon-xiangyou"></span></a></li>';
                }
            });
            html+='</ul>';
            $li.append(html);
        });
        $.each($rootLi.find("a"),function () {
            var $a=$(this);
            var $ul=$a.siblings("ul");
            if($ul.children().length==0){
                $a.addClass("billing-leaf");
                $ul.remove();
                var $spans=$a.children("span");
                $spans.each(function () {
                    if($(this).hasClass("icon")) $(this).remove();
                });
            }
        });
        $tree.find("li").on("click",function () {
            var $li=$(this);
            expand($li);
            leafClick($(this));
            return false;
        });
		$tree.find("a").on("click",function () {
            options.onclick($(this));
        });
		$rootA.click();
    }

    //控制菜单展开和收缩的方法，会根据是否有menuLeaf这个叶子节点标签来进行判断
    function expand($li) {
        var $a=$li.children("a:first");
        var $icon=$a.find("span.icon");
        if(!$a.hasClass("billing-leaf")) {
            var $ul = $a.siblings("ul");
            if ($ul.attr("node-expanded") == "false") {
                $ul.slideDown();
                $ul.attr("node-expanded", "true");
            } else {
                $ul.slideUp();
                $ul.attr("node-expanded", "false")
            }
            arrowIconRotate($icon);
        }
        var $liSiblings=$li.siblings("li");
        if($li.children("ul").attr("node-expanded")){
            $liSiblings.each(function () {
                var $this=$(this);
                var $a=$this.children("a");
                var $ul=$this.children("ul");
                var $icon=$a.find("span.icon");
                if($ul.attr("node-expanded")=="true"){
                    $ul.slideUp();
                    $ul.attr("node-expanded","false");
                    arrowIconRotate($icon);
                }
            });
        }
    }

    //控制右侧三角标签旋转的方法
    function arrowIconRotate($icon) {
        if($icon.hasClass("arrow-rotate")){
            $icon.addClass("arrow-rotate-recover");
            $icon.removeClass("arrow-rotate");
        }else{
            $icon.addClass("arrow-rotate");
            $icon.removeClass("arrow-rotate-recover");
        }
    }

    //控制菜单获取失去焦点的方法
    function leafClick($li) {
        var $a=$li.find("a:first span");
        if($a.hasClass("billing-leaf")){
            $a.parents(".billing-tree").find(".billing-leaf").removeClass("billing-leaf-selected");
            $a.addClass("billing-leaf-selected");
        }
    }
}